<template>
  <div style="height: 100vh; width: 100vw">
    <VueFlow v-model:nodes="nodes" v-model:edges="edges" :fitView="true">
      <template #node-custom="customNodeProps">
        <CustomNode v-bind="customNodeProps" />
      </template>
      <Panel>
        <button @click="convertToSnakeLayout">切换布局</button>
        <button @click="addNode">新增</button>
      </Panel>
    </VueFlow>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Panel, useVueFlow, VueFlow } from '@vue-flow/core';
import CustomNode from '@/pages/vueflow/components/CustomNode.vue';
import { isStraightFlow, sortNodesByEdges, useSnakeLayoutHook } from '@/hooks/vueflowHooks';
import { MessagePlugin } from 'tdesign-vue-next';

const nodes = ref([]);
const edges = ref([]);

const instance = useVueFlow();
const { onConnect, addEdges, onEdgeUpdateEnd, applyEdgeChanges, fitView, applyNodeChanges } = instance;
onConnect(addEdges);

// 初始化线性布局的节点
const initLinearFlow = () => {
  const initialNodes = Array.from({ length: 25 }, (v, i) => ({
    id: `node-${i}`,
    type: 'custom',
    position: { x: 0, y: i * 100 }, // 初始竖直排列
    data: { label: `Node ${i}` },
  }));

  const initialEdges = [];

  for (let i = 0; i < initialNodes.length - 1; i++) {
    initialEdges.push({
      id: `edge-${i}`,
      source: `node-${i}`,
      target: `node-${i + 1}`,
    });
  }

  nodes.value = initialNodes;
  edges.value = initialEdges;
};

// 转换为蛇形布局
const convertToSnakeLayout = () => {
  nodes.value = useSnakeLayoutHook(nodes.value, edges.value);
};

const addNode = () => {
  const newId = `node-${nodes.value.length}`;
  const newNode = {
    id: newId,
    type: 'custom',
    position: { x: 220, y: 220 }, // 初始位置
    data: { label: `Node ${nodes.value.length}` },
  };
  nodes.value.push(newNode);
};

onMounted(() => {
  // 初始化数据
  initLinearFlow();
});
</script>

<style>
/* 添加一些基本样式 */
.vue-flow__controls {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 10;
}
</style>
